<?php
Yii::import('application.behaviors.CArJSON');
class MessageController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        /*$model=new Message;

          // Uncomment the following line if AJAX validation is needed
          // $this->performAjaxValidation($model);

          if(isset($_POST['Message']))
          {
              $model->attributes=$_POST['Message'];
              if($model->save())
                  $this->redirect(array('view','id'=>$model->id));
          }

          $this->render('create',array(
              'model'=>$model,
          ));*/
        $userId=1;
        $data = CJSON::decode(file_get_contents('php://input'));
        $model = new Message();
        $model->subject = isset($data['subject'])?$data['subject']:'';
        $model->thread_id = isset($data['thread_id'])?$data['thread_id']:'';
        $model->message = $data['message'];
        //This is an array.
        /*$model->state="US";*/
        $model->create_time = date('Y-m-d h:i:s');
        $model->last_update = date('Y-m-d h:i:s');
        $model->sending_user_id=$userId;
        $model->status = 'S';
        $model->id = null;
        if (isset($data['saveOnly']) && $data['saveOnly'] != 0) {
            $model->status = 'U';
        }

        if (!$model->save(false)) {
            $errors = array();
            foreach ($model->getErrors() as $e) $errors = array_merge($errors, $e);
            $this->sendResponse(500, implode("<br />", $errors));
        }
        if(isset($data['to'])){
            $receiverStr = $data['to'];
            $receiverStr = str_replace(' ', '', $receiverStr);
            $receivers = explode(',', $receiverStr);
            $receiver=$receivers[0];
            //Find thread:
            $thread=UserFriend::model()->findByAttributes(array('user_id'=>$userId,'friend_id'=>$receiver));
            if($thread){
                $threadId=$thread->id;
                $thread->last_activity=time();
                $thread->update(array('last_activity'));
            }
            else {
                $thread=new UserFriend();
                $thread->user_id=$userId;
                $thread->friend_id=$receiver;
                $thread->last_activity=time();
                $thread->id=null;
                $thread->save();
                $threadId=$thread->id;
            }
            //Store sender
            $messageUser = new MessageUser();
            $messageUser->message_id = $model->id;
            $messageUser->user_id = $userId; //TODO: hard code here, will remove it after we have finished the user module.
            $messageUser->ownership = Message::SENDER;
            $messageUser->status = Message::SENT;
            $messageUser->id = null;
            $messageUser->save(false);
            /*if (count($receivers)) {
                foreach ($receivers as $receiver) {*/
                    $messageUser1 = new MessageUser();
                    $messageUser1->user_id = $receiver;
                    $messageUser1->ownership = Message::RECEIVER;
                    $messageUser1->message_id = $model->id;
                    $messageUser1->status = Message::UNREAD;
                    $messageUser1->save(false);
              /*  }
            }*/

            $model->thread_id=$threadId;
            $model->update(array('thread_id'));
        }



        /*$json = new CArJSON();
        // Define which relations do you want to load
        $relations = array('message');
        $this->sendResponse(200, $json->toJSON($messageUser, $relations));*/
        $this->sendResponse(200, CJSON::encode($model));
    }

    /**
     * Read message need to update message status.
     * @param $id
     */
    public function actionRead($id)
    {
        $messageId = $id;

        $messageUser = MessageUser::model()->findByPk($messageId);
        $messageUser->status = "R";
        $messageUser->update(array('status'));
        $this->sendResponse(200);
    }

    public function actionUnRead($id)
    {
        $messageId = $id;
        $messageUser = MessageUser::model()->findByPk($messageId);
        $messageUser->status = "R";
        $messageUser->update(array('status'));
        $this->sendResponse(200);

    }

    public function actionReadAll($userId)
    {
        $selected = array();
        //TODO: We must implement the
        $messageUser = MessageUser::model()->findAllByAttributes(array('user_id' => $userId, 'ownership' => 'R'));
        $messageUser->status = "R";
        $messageUser->updateAll(array('status'));
    }


    public function actionInbox()
    {
        $criteria = new CDbCriteria();
        //Hard Code:
        $userId = 1;
        $criteria->order = "id ASC";
        //$criteria->compare('ownership','R');
        $criteria->compare('user_id', $userId);
        $criteria->select = "message_id";
        $criteria->distinct = true;
        $messages = MessageUser::model()->findAll($criteria);

        // $json = new CArJSON();
        // Define which relations do you want to load
//        $relations = array('message');
        $messages = CHtml::listData($messages, 'message_id', 'message_id');
        $models = array();
        if (count($messages)) {
            $criteria1 = new CDbCriteria();
            $criteria1->addInCondition('id', array_values($messages));
            $models = Message::model()->findAll($criteria1);
        }
//CVarDumper::dump($userModels,10,true);die;
        //echo $json->toJSON($models, $relations);
//        $this->sendResponse(200, $json->toJSON($messages, $relations));
        $this->sendResponse(200, CJSON::encode($models));
    }

    public function actionThread()
    {
        $criteria = new CDbCriteria();
        //Hard Code:
        $userId = 1;
        $criteria->order = "last_activity DESC";

        //$criteria->compare('ownership','R');
        $criteria->compare('user_id', $userId);
        $thread = UserFriend::model()->findAll($criteria);
        $json = new CArJSON();
        $relations = array('friend','messages','latestMessage');
        $this->sendResponse(200, $json->toJSON($thread, $relations));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Message'])) {
            $model->attributes = $_POST['Message'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        /* for($i=1;$i<60;$i++){
            $message=new Message();
            $message->subject="Message $i";
             $message->message="This is the sample content for message $i, Please check it.";
             $message->status="U";
            $message->create_time=date('Y-m-d');
            $message->last_update=date('Y-m-d');
             $message->parent_id=0;
             $message->save();
         }*/
        /*$messages= Message::model()->findAll();
        foreach($messages as $message){
            $userMessage=new MessageUser();
            $userMessage->message_id=$message->id;
            $userMessage->user_id=2;
            $userMessage->status='S';
            $userMessage->ownership='S';
            $userMessage->save();

            $userMessage1=new MessageUser();
            $userMessage1->message_id=$message->id;
            $userMessage1->user_id=1;
            $userMessage1->status='U';
            $userMessage1->ownership='R';
            $userMessage1->save();
        }*/
        /*$dataProvider=new CActiveDataProvider('Message');
          $this->render('index',array(
              'dataProvider'=>$dataProvider,
          ));*/
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Message('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Message']))
            $model->attributes = $_GET['Message'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Message::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'message-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
